//
//  NSURLextension.m
//  WebClipper
//
//  Created by Daniel Braun on 07/02/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "NSURLextension.h"
#import "StringExtension.h"

@implementation  NSURL (PatchingVariables)

- (NSURL *) urlByChangingQueryVariable:(NSString *)varName toEncodedValue:(NSString *)v orCreate:(bool)create
{
	NSString *q=[self query];
	NSString *rs=[[self absoluteString] stringBetween:nil and:@"?" inclusive:NO];
	NSMutableArray *vars=[[q componentsSeparatedByString:@"&"] mutableCopy];
	NSString *prefix=[NSString stringWithFormat:@"%@=", varName];
	NSString *kv=[NSString stringWithFormat:@"%@=%@",  
			     [varName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], v];
	NSUInteger i, count = [vars count];
	BOOL found=NO;
	for (i = 0; i < count; i++) {
		NSString * v = [vars objectAtIndex:i];
		if ([v hasPrefix:prefix]) {
			[vars replaceObjectAtIndex:i withObject:kv];
			found=YES;
			break;
		}
	}
	if (!found) {
		if (!create) return self;
		[vars addObject:kv];
	}
	NSString *nq=[vars componentsJoinedByString:@"&"];
	NSURL *u=[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", rs, nq]];
	return u;
}

@end
